package cn.wolfcode.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisDemoController
 * @Description redis.redisson框架实现分布式锁
 * @Author xdzhango
 * @Date 2020/4/24 15:10
 **/
@RestController
public class RedisDemoController {

    @Autowired
    private Redisson redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/deduct_stock")
    public String deductStock(){
        String lockKey = "product_001";

        String clietId = UUID.randomUUID().toString();
        RLock redissonLock = redisson.getLock(lockKey);

        try{
            //加锁
            //Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,clietId);
            //设置redis超时时间
            //stringRedisTemplate.expire(lockKey,10,TimeUnit.SECONDS);

            //set nx + expire一起  redis保证原子性
            //Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey,clietId,10,TimeUnit.SECONDS); //jedis.setnx
            //if (!result){
            //return "error";
            //}

            //redisson框架  底层会自动去给超时时间续命 参照resource文档redis文件
            redissonLock.lock(30,TimeUnit.SECONDS);
            //假设库存里面有50个
            stringRedisTemplate.opsForValue().set("stock","50");
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock > 0){
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock",realStock+"");//jedis.set(key,value)
                System.out.println("扣减成功,剩余库存:"+realStock +"");
            }else{
                System.out.println("扣减失败,库存不足");
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            redissonLock.unlock();
            /*//释放锁
            if (clietId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
                stringRedisTemplate.delete(lockKey);
            }*/
        }
        return "end";
    }

}
